package com.chima.action;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;

import java.io.OutputStream;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;

import com.chima.domain.JobDetail;
import com.chima.service.JobDetailService;
import com.opensymphony.xwork2.ActionSupport;

public class LoadAction extends ActionSupport  {
	
	
    private JobDetailService jobDetailService;
    private int  id;
    
	public int getId() {
		return id;
	}



	public void setId(int id) {
		this.id = id;
	}



	public JobDetailService getJobDetailService() {
		return jobDetailService;
	}



	public void setJobDetailService(JobDetailService jobDetailService) {
		this.jobDetailService = jobDetailService;
	}



	
public String execute() throws Exception {
	
	          
	          JobDetail j=jobDetailService.findById(id);
			// 解决请求参数中文件名get乱码
	         
	           String filename=j.getFujian();
  		try {
	  		    ServletContext servletContext = ServletActionContext.getServletContext();
				String downloadDir = servletContext.getRealPath("/upload");
				//处理中文 GBK ISO-8859-1
				String cnData = filename.substring(0,filename.lastIndexOf("."));
				// 处理
				cnData = new String(cnData.getBytes("GBK"),"ISO-8859-1");
				
				String extName = filename.substring(filename.lastIndexOf("."));
				
				BufferedInputStream bs=new BufferedInputStream(new FileInputStream(new File(downloadDir, filename)));
				
				HttpServletResponse response = ServletActionContext.getResponse();
				OutputStream os = response.getOutputStream();// 取得输出流
				byte buffBytes[] = new byte[1024];
			
				response.reset();// 清空输出流
				// 设定输出文件头
				response.setHeader("Content-disposition", "attachment; filename="+ cnData + extName);
				response.setContentType("application/octet-stream;charset=UTF-8");
				int read = 0;
				while ((read = bs.read(buffBytes)) != -1) {
					os.write(buffBytes, 0, read);
				}
				os.flush();
				os.close();
				bs.close();
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		return NONE;
	}

}
